﻿using AutoMapper;
//using B.S.DataBase.MyProject.ErrorCode;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.settingCommand;
using MyMES.Writer.API.FileNlog;

namespace MyMES.Writer.API.Application.CommendHandlers.settingCommand
{
    public class AddCommandHandlers : IRequestHandler<AddCommand, APIResult<Warehouse>>
    {
        private readonly IBaseRepository<Warehouse> accreop;
        private readonly IMapper mapper;
        private readonly Nolgs nlogs;

        public AddCommandHandlers(IBaseRepository<Warehouse> accreop,IMapper mapper,Nolgs nlogs)
        {
            this.accreop = accreop;
            this.mapper = mapper;
            this.nlogs = nlogs;
        }
        /// <summary>
        /// 添加仓库
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<Warehouse>> Handle(AddCommand request, CancellationToken cancellationToken)
        {
            var startTime= DateTime.Now;
            try
            {
                APIResult<Warehouse> result = new APIResult<Warehouse>();
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";
                var model = mapper.Map<Warehouse>(request);
                string sql = "insert into Warehouse(warehouseId,WarehouseCode, WarehouseName, warehouseposition, Warehousearea, Warehousepeople, IsFrozen, Warehousenotes, libraryId,IsDelete) values(@warehouseId,@WarehouseCode, @WarehouseName, @warehouseposition, @Warehousearea, @Warehousepeople, @IsFrozen, @Warehousenotes, @libraryId,@IsDelete)";
                await accreop.Insert(model, sql);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = System.DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nlogs.GetNlogs(
                    request.WarehouseName ?? "Unknow", "仓库添加", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
